package com.gitee.wsl.io

import kotlinx.io.Buffer
import kotlinx.io.readByteArray
import java.util.zip.Deflater
import java.util.zip.Inflater

private const val CHUNK_SIZE: Int = 4096

actual fun deflate(buffer: Buffer): Buffer {
    val deflater = Deflater()
    deflater.setInput(buffer.readByteArray())
    deflater.finish()
    val compressed = Buffer()
    val chunkBuffer = ByteArray(CHUNK_SIZE)
    while (!deflater.finished()) {
        val bytesCompressed = deflater.deflate(chunkBuffer)
        compressed.write(chunkBuffer, 0, bytesCompressed)
    }
    deflater.end()
    return compressed
}

actual fun inflate(buffer: Buffer): Buffer {
    val inflater = Inflater()
    inflater.setInput(buffer.readByteArray())
    val decompressed = Buffer()
    val chunkBuffer = ByteArray(CHUNK_SIZE)
    while (!inflater.finished()) {
        val bytesDecompressed = inflater.inflate(chunkBuffer)
        decompressed.write(chunkBuffer, 0, bytesDecompressed)
    }
    inflater.end()
    return decompressed
}